package com.ruoyi.kindergarten.util;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class MinioUtil {
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;
    @Value("${minio.endpoint}")
    private String endpoint;

    public void checkAndCreateBucket(String bucketName) throws Exception {
        if(!minioClient.bucketExists(BucketExistsArgs.builder().bucket(this.bucketName).build())){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(this.bucketName).build());
        }
    }

    public String uploadFile(MultipartFile file, String objectName) throws Exception {
        // 检查默认桶是否存在
        checkAndCreateBucket(bucketName);
        // 上传文件
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build()
        );

        // 返回访问路径（需确保桶有公开访问权限，或通过预签名 URL 访问）
        return endpoint + "/" + bucketName + "/" + objectName;
    }

}
